<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Services\Form\initFormData as InitFormData;
use Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cookie;

class UC extends Controller
{
    use \App\Traits\ApiTrait, \App\Traits\CacheTrait;
    public $curl;
    public $errMsg = ['code'=>'-1','msg'=>'未知的错误!'];
    public $commonMsg = ['code'=>'1','msg'=>'success'];
    // 正式环境java接口基础URL
    public $apiBaseUri='api.crm.tanwin.cn/';
    // 测试环境java接口基础URL
    // public $apiBaseUri='192.172.3.139:8080/';
    private $apiLoginUri='ctm/v1/login';
    private $apiCodeUri='ctm/v1/getYzm';
    private $apiMsgCenterUri='information/list';
    private $apiMsgUnreadUri='information/listIsnotread';
    private $msgPageSize='100';
    private $msgPageNum='1';
    private $apiRegistUri='ctm/v1/register';
    private $apiMsgDetailUri='informationread/search';
    private $apiMsgDelUri='information/delete';
    private $apiProfileUpdateUri='ctm/v1/perfectPersonalInfos';
    private $apiProfileUri='ctm/v1/getPersonalinfo';
    private $apiDownUri='files/fileslist';
    private $apiDownCateUri='files/getPageManage';
    private $apiActivityUri='activity/futureActivityList';
    private $apiSignUri='activitydetail/signup';
    private $apiActivityInfoUri='activity/viewActivity';
    private $apiArticleListUri='article/findByProgramaId';
    private $apiArticleUri='article/selectById';

    public function __construct(Request $request, InitFormData $formData)
    {
        $this->curl = new \Ixudra\Curl\CurlService();
        $this->request = $request;
        $this->formData = $formData;
        $this->breadMenuList = config('front.bread_menu');

    }

    public function index(Request $request){
      $phone = $request->cookie('phone');
      $userId= $request->cookie('userId');
      //验证是否有cookie信息
      if($phone!=0 && $phone!=null){
        $data=['phone'=>$phone];
        $data['userId']=$userId;
        $rqUrl=$this->apiBaseUri.$this->apiMsgUnreadUri;
        $rqData=['personal_mobile'=>$phone,'fromRequest'=>'tanwin','pageNumber'=>1,'pageSize'=>10,'personal_id'=>$userId];
        $result=$this->curl->to($rqUrl)
        ->withOption('TIMEOUT', 10)
        ->withData($rqData)
        ->post();
        try {
          $result=json_decode($result,true);
          // print_r($result);
          $data['count']=$result['data']['total']-1;
        } catch (Exception $e) {
          $data['count']=0;
        }
        return \response()
             ->view('web.uc.welcome', $data)
             ->withCookie(cookie('phone',$phone,120))
             ->withCookie(cookie('userId',$userId,120));
      }
      return \response()
           ->view('web.uc.login');
    }

    public function regist(Request $request){
      $phone = $request->cookie('phone');
      $userId=$request->cookie('userId');
      //验证是否有cookie信息
      if($phone==0 || $phone==null){
        return \response()
             ->view('web.uc.regist');
           }
      else{
        return redirect('/uc');
      }

    }

    public function ajaxRegist(Request $request){
      $phone = $request->cookie('phone');
      $userId=$request->cookie('userId');
      //验证是否有cookie信息
      if($phone==0 || $phone==null){
        if($request->phone!=0){
          $phone=$request->phone;
          $code=$request->code;
          $data=['phone'=>$phone];
          $rqUrl=$this->apiBaseUri.$this->apiRegistUri;
          $rqData=['personal_mobile'=>$_REQUEST['phone'],'yzm'=>$code,'fromRequest'=>'tanwin'];
          $result=$this->curl->to($rqUrl)
          ->withOption('TIMEOUT', 10)
          ->withData($rqData)
          ->post();
          if($result!=null && $result!=''){
            $result=json_decode($result,true);
            if($result['code']==100){
              $cookie=['phone',$phone,120];
              $userId=$result['data']['personal_id'];
              return response(json_encode($this->commonMsg))
              ->withCookie(cookie('phone',$phone,120))
              ->withCookie(cookie('userId',$userId,120));
            }
            else{
              $this->errMsg['msg'] = $result['msg'];
              return response(json_encode($this->errMsg));
            }
          }
          else{
            $this->errMsg['msg']='注册出错了，请联系管理员！';
            return response(json_encode($this->errMsg));
          }
        }
        else{
          $this->errMsg['msg']='手机输入不正确';
          return response(json_encode($this->errMsg));
        }
      }
      //已有有效cookie则跳转至登录后页面
      $this->errMsg['msg']='您当前已登录!';
      return response(json_encode($this->errMsg))
      ->withCookie(cookie('phone',$phone,120))
      ->withCookie(cookie('userId',$userId,120));
    }

    public function login(Request $request){
      $phone = $request->cookie('phone');
      $userId= $request->cookie('userId');
      //验证是否有cookie信息
      if($phone!=0 && $phone!=null){
        $data=['phone'=>$phone];
        return \response()
             ->view('web.uc.index', $data)
             ->withCookie(cookie('phone',$phone,120))
             ->withCookie(cookie('userId',$userId,120));
      }
      return \response()
           ->view('web.uc.login');
    }

 /*
  * ajax登录的响应接口
  */
    public function ajaxLogin(){
      //验证是否正确输入，正确则执行
      if(isset($_REQUEST['phone']) && $_REQUEST['phone']!=0 && isset($_REQUEST['code']) && $_REQUEST['code']!=0){
        $phone = $_REQUEST['phone'];
        $code = $_REQUEST['code'];
        //判断输入的验证码是否正确
        $dbCode=DB::table('sms_code_log')->where(['phone'=>$phone,'code'=>$code])->first();
        if(isset($dbCode->code) && $code == $dbCode->code){
          $loginUrl=$this->apiBaseUri.$this->apiLoginUri;
          $result=$this->curl->to($loginUrl)
          ->withOption('TIMEOUT', 10)
          ->withData(['personal_mobile'=>$phone,'yzm'=>$code])
          ->post();
          if($result!=null && $result!=''){
              $result=json_decode($result,true);
              if($result['code']==200){
                $cookie=['phone',$phone,120];
                if($phone=='18058715658')
                $userId='40b7921181b64526a1764a4b45eebeb7';
                else $userId=$result['personal_id'];
                $headPic='img/nav/pic1.jpg';
                if($result['personal_headshot']!='')
                $headPic=$result['personal_headshot'];
                $this->commonMsg['pid']=$userId;
                return response(json_encode($this->commonMsg))
                ->withCookie(cookie('userId',$userId,120))
                ->withCookie(cookie('phone',$phone,120))
                ->withCookie(cookie('headPic',$headPic,120));
                // ->withCookie(cookie($phone,$phone,120))
                // ->withCookie(cookie($userId,$phone,120));
              }
              else{
                $this->errMsg['msg'] = $result['msg'];
                echo json_encode($this->errMsg);
              }
          }
          else{
            $this->errMsg['msg']='验证码不正确或已过期，请重新尝试';
            echo json_encode($this->errMsg);
          }
        }
        else {
          $this->errMsg['msg']='验证码不正确或已过期，请重新尝试';
          echo json_encode($this->errMsg);
        }
      }
      //输入错误则直接输出错误提示
      else{
        // var_dump($_REQUEST['phone']);
        $this->errMsg['msg'] = '填写不正确！';
        echo json_encode($this->errMsg);
      }
    }

    public function ajaxLogOut(Request $request){
        return response(json_encode($this->commonMsg))
        ->withCookie(cookie('userId','0',-1))
        ->withCookie(cookie('phone','0',-1));
    }

    public function ajaxSendSms(){
        if(isset($_REQUEST['phone']) && $_REQUEST['phone']!=0){
          $rqUrl=$this->apiBaseUri.$this->apiCodeUri;
          $rqData=['personal_mobile'=>$_REQUEST['phone'],'fromRequest'=>'tanwin'];
          $result=$this->curl->to($rqUrl)
          ->withOption('TIMEOUT', 10)
          ->withData($rqData)
          ->post();
          if($result!='' && $result!=null){
            $result=json_decode($result,true);
            if($result['code']==100){
              echo json_encode($this->commonMsg);
            }
            else{
              $this->errMsg['msg']=$result['msg'];
              echo json_encode($this->errMsg);
            }
          }
          else{
            $this->errMsg['msg']='发送失败';
            echo json_encode($this->errMsg);
          }
        }
        else echo json_encode($this->errMsg);
    }

    public function activity(Request $request){
      $phone = $request->cookie('phone');
      $userId = $request->cookie('userId');
      if(isset($request->pageNumber) && $request->pageNumber!=0)$pageNumber=$request->pageNumber;
      else $pageNumber=1;
      $pageSize=6;
      // $pageNumber=$this->msgPageNum;
      //验证是否有cookie信息
      if($phone!=0 && $phone!=null){
        $data=['phone'=>$phone];
        $rqUrl=$this->apiBaseUri.$this->apiActivityUri;
        $rqData=['personal_mobile'=>$phone,'fromRequest'=>'tanwin','pageNumber'=>$pageNumber,'pageSize'=>$pageSize];
        $result=$this->curl->to($rqUrl)
        ->withOption('TIMEOUT', 10)
        ->withData($rqData)
        ->post();
        // print_r('请求URL是'.$rqUrl.'</br>结果是'.$result);
        // die;
        try {
            $result=json_decode($result,true);
            if($result['code']==100){
              $rData=$result['data'];
              $data['data']=$rData;
              $data['phone']=$phone;
              $data['id']=$userId;
              return \response()
                   ->view('web.uc.activity', $data)
                   ->withCookie(cookie('phone',$phone,120))
                   ->withCookie(cookie('userId',$userId,120));
            }
            else{
              return \response("服务器请求错误，请重试。")
                   ->withCookie(cookie('phone',$phone,120))
                   ->withCookie(cookie('userId',$userId,120));
            }
          } catch (Exception $e) {
            $data['data']=null;
            $data['phone']=$phone;
            $data['id']=$userId;
            return \response()
                 ->view('web.uc.activity',$data)
                 ->withCookie(cookie('phone',$phone,120))
                 ->withCookie(cookie('userId',$userId,120));
          }
      }

      //不包含有效cookie则跳转至登录
      return redirect('/login');
    }

    public function ajaxSign(Request $request){
      $phone = $request->cookie('phone');
      $userId=$request->cookie('userId');
      $id=$request->id;
      // $pageNumber=$this->msgPageNum;
      //验证是否有cookie信息
      if($phone!=0 && $phone!=null){
        $data=['phone'=>$phone];
        $rqUrl=$this->apiBaseUri.$this->apiSignUri;
        $rqData=['personal_mobile'=>$phone,'fromRequest'=>'tanwin','activity_id'=>$id];
        $result=$this->curl->to($rqUrl)
        ->withOption('TIMEOUT', 10)
        ->withData($rqData)
        ->post();
        // print_r($result);
        // die;
        try {
            $result=json_decode($result,true);
            if($result['code']==100){
              $rData=$result['data'];
              $data['data']=$rData;
              $data['phone']=$phone;
              $data['id']=$userId;
              $data['code']=1;
              $data['msg']='报名成功，请保持电话畅通！';
              return response(json_encode($data))
                   ->withCookie(cookie('phone',$phone,120))
                   ->withCookie(cookie('userId',$userId,120));
            }
            $data['code']=-1;
            $data['msg']=$result['msg'];
            return response(json_encode($data))
                 ->withCookie(cookie('phone',$phone,120))
                 ->withCookie(cookie('userId',$userId,120));
          } catch (Exception $e) {
            $result=json_decode($result,true);
            $data['data']=null;
            $data['phone']=$phone;
            $data['id']=$userId;
            $data['code']=-1;
            $data['msg']=$result['msg'];
            return response(json_encode($data))
                 ->withCookie(cookie('phone',$phone,120))
                 ->withCookie(cookie('userId',$userId,120));
          }
      }
      else{
        //不包含有效cookie则跳转至登录
        $data=['code'=>-1,'msg'=>'请重新登录'];
        return response(json_encode($data))
             ->withCookie(cookie('phone',$phone,120))
             ->withCookie(cookie('userId',$userId,120));
      }

    }

    public function activityInfo(Request $request){
      $phone = $request->cookie('phone');
      $userId=$request->cookie('userId');
      $id=$request->id;
      // $pageNumber=$this->msgPageNum;
      //验证是否有cookie信息
      if($phone!=0 && $phone!=null){
        $data=['phone'=>$phone];
        $rqUrl=$this->apiBaseUri.$this->apiActivityInfoUri;
        $rqData=['personal_mobile'=>$phone,'fromRequest'=>'tanwin','id'=>$id];
        $result=$this->curl->to($rqUrl)
        ->withOption('TIMEOUT', 10)
        ->withData($rqData)
        ->post();
        // print_r($result);
        // die;
        try {
            $result=json_decode($result,true);
            if($result['code']==100){
              $rData=$result['data'];
              $data['data']=$rData;
              $data['phone']=$phone;
              $data['id']=$userId;
              return \response()
                   ->view('web.uc.activityInfo', $data)
                   ->withCookie(cookie('phone',$phone,120))
                   ->withCookie(cookie('userId',$userId,120));
            }
            else{
              return \response("服务器请求错误，请重试。")
                   ->withCookie(cookie('phone',$phone,120))
                   ->withCookie(cookie('userId',$userId,120));
            }
          } catch (Exception $e) {
            $data['data']=null;
            $data['phone']=$phone;
            $data['id']=$userId;
            return \response()
                 ->view('web.uc.activityInfo',$data)
                 ->withCookie(cookie('phone',$phone,120))
                 ->withCookie(cookie('userId',$userId,120));
          }
      }
      else
      //不包含有效cookie则跳转至登录
      return redirect('/login');
    }

    public function msgCenter(Request $request){
      $phone = $request->cookie('phone');
      $userId=$request->cookie('userId');
      // $pageNumber=$this->msgPageNum;
      if(isset($request->pageNumber) && $request->pageNumber!=0)$pageNumber=$request->pageNumber;
      else $pageNumber=1;
      $pageSize=$this->msgPageSize;
      //验证是否有cookie信息
      if($phone!=0 && $phone!=null){
        $data=['phone'=>$phone];
        $rqUrl=$this->apiBaseUri.$this->apiMsgUnreadUri;
        // print_r('请求地址是'.$rqUrl);
        // print_r('请求参数personal_id为'.$userId);
        $rqData=['personal_mobile'=>$phone,'fromRequest'=>'tanwin','pageNumber'=>$pageNumber,'pageSize'=>$pageSize,'personal_id'=>$userId];
        $result=$this->curl->to($rqUrl)
        ->withOption('TIMEOUT', 10)
        ->withData($rqData)
        ->post();
        // die;
        //  print_r('请求结果是'.$result);
        //  die;
        $result=json_decode($result,true);
        // print_r('请求结果是'.$result['data']);
        // $unread=$result['data']['records'];
        // var_dump($unread);
        // die;
        // $unread=['data'=>[],'count'=>0];
        $rData=$result['data']['records'];
        $unread=$rData;
        $rqUrl=$this->apiBaseUri.$this->apiMsgCenterUri;
        $rqData=['personal_mobile'=>$phone,'fromRequest'=>'tanwin','pageNumber'=>$pageNumber,'pageSize'=>$pageSize,'personal_id'=>$userId];
        $result=$this->curl->to($rqUrl)
        ->withOption('TIMEOUT', 10)
        ->withData($rqData)
        ->post();
        $result=json_decode($result,true);
        $read=$result['data']['records'];
        $data['read']=$read;
        $data['unread']=$unread;
        return \response()
             ->view('web.uc.msgCenter', $data)
             ->withCookie(cookie('phone',$phone,120))
             ->withCookie(cookie('userId',$userId,120));
      }

      //不包含有效cookie则跳转至登录
      return redirect('/login');
    }

    public function msgDetail(Request $request){
      $phone = $request->cookie('phone');
      $userId=$request->cookie('userId');
      //验证是否有cookie信息
      if($phone!=0 && $phone!=null){
        $rqUrl=$this->apiBaseUri.$this->apiMsgDetailUri;
        $information_id=$request->id;
        $rqData=['personal_id'=>$userId,'information_id'=>$information_id,'personal_mobile'=>$phone,'fromRequest'=>'tanwin'];
        $result=$this->curl->to($rqUrl)
        ->withOption('TIMEOUT', 10)
        ->withData($rqData)
        ->post();
        // print_r($result);
        return response($result)
             ->withCookie(cookie('phone',$phone,120))
             ->withCookie(cookie('userId',$userId,120));
      }
      //不包含有效cookie则跳转至登录
      return redirect('/login');
    }

    public function userInfo(Request $request){
      $phone = $request->cookie('phone');
      $userId= $request->cookie('userId');
      $id=$request->id;
      //验证是否有cookie信息
      if($phone!=0 && $phone!=null){
        $data=['phone'=>$phone];
        $rqUrl=$this->apiBaseUri.$this->apiProfileUri;
        $rqData=['personal_mobile'=>$phone,'fromRequest'=>'tanwin'];
        $result=$this->curl->to($rqUrl)
        ->withOption('TIMEOUT', 10)
        ->withData($rqData)
        ->post();
        // print_r($result);
        // die;
        try {
            $result=json_decode($result,true);
            if($result['code']==100){
              $rData=$result['data'];
              $data['data']=$rData;
              $data['phone']=$phone;
              $data['id']=$userId;
              return \response()
                   ->view('web.uc.userInfo', $data)
                   ->withCookie(cookie('phone',$phone,120))
                   ->withCookie(cookie('userId',$userId,120));
            }
            else{
              return \response("服务器请求错误，请重试。")
                   ->withCookie(cookie('phone',$phone,120))
                   ->withCookie(cookie('userId',$userId,120));
            }
          } catch (Exception $e) {
            $data['data']=null;
            $data['phone']=$phone;
            $data['id']=$userId;
            return \response()
                 ->view('web.uc.userInfo',$data)
                 ->withCookie(cookie('phone',$phone,120))
                 ->withCookie(cookie('userId',$userId,120));
          }
        }

      //不包含有效cookie则跳转至登录
      return redirect('/login');
    }

    public function DownCate(Request $request){
      $phone = $request->cookie('phone');
      $userId= $request->cookie('userId');
      //验证是否有cookie信息
      if($phone!=0 && $phone!=null){
        $data=['phone'=>$phone];
        $rqUrl=$this->apiBaseUri.$this->apiDownCateUri;
        $rqData=['personal_mobile'=>$phone,'fromRequest'=>'tanwin'];
        $result=$this->curl->to($rqUrl)
        ->withOption('TIMEOUT', 10)
        ->withData($rqData)
        ->post();
        // print_r($result);
        try {
            $result=json_decode($result,true);
            if($result['code']==100){
              $rData=$result['data'];
              $data['code']=1;
              $data['data']=$rData;
              $data['phone']=$phone;
              $data['id']=$userId;
              return \response()
                   ->view('web.uc.down', $data)
                   ->withCookie(cookie('phone',$phone,120))
                   ->withCookie(cookie('userId',$userId,120));
            }
            else{
              return \response("服务器请求错误，请重试。")
                   ->withCookie(cookie('phone',$phone,120))
                   ->withCookie(cookie('userId',$userId,120));
            }
          } catch (Exception $e) {
            $data['code']=-1;
            $data['data']=null;
            $data['phone']=$phone;
            $data['id']=$userId;
            return \response()
                 ->view('web.uc.down', $data)
                 ->withCookie(cookie('phone',$phone,120))
                 ->withCookie(cookie('userId',$userId,120));
          }
        }

      //不包含有效cookie则跳转至登录
      return redirect('/login');
    }


    public function ajaxDownList(Request $request){
      $phone = $request->cookie('phone');
      $userId= urldecode($request->cookie('userId'));
      if(isset($request->pageNumber) && $request->pageNumber!=0)$pageNumber=$request->pageNumber;
      else $pageNumber=1;
      $pageSize=$this->msgPageSize;
      $id=$request->id;
      //验证是否有cookie信息
      if($phone!=0 && $phone!=null){
        $data=['phone'=>$phone];
        $rqUrl=$this->apiBaseUri.$this->apiDownUri;
        $rqData=['personal_mobile'=>$phone,'fromRequest'=>'tanwin','pageSize'=>$pageSize,'pageNumber'=>$pageNumber,'file_manage_id'=>$id];
        $result=$this->curl->to($rqUrl)
        ->withOption('TIMEOUT', 10)
        ->withData($rqData)
        ->post();
        // print_r($result);
        // die;
        try {
            $result=json_decode($result,true);
            if($result['code']==100){
              $rData=$result['data'];
              $data['data']=$rData;
              $data['phone']=$phone;
              $data['id']=$userId;
              return response(json_encode($data))
                   ->withCookie(cookie('phone',$phone,120))
                   ->withCookie(cookie('userId',$userId,120));
            }
          } catch (Exception $e) {
            $data['data']=null;
            $data['phone']=$phone;
            $data['id']=$userId;
            return response(json_encode($data))
                 ->withCookie(cookie('phone',$phone,120))
                 ->withCookie(cookie('userId',$userId,120));
          }
        }

      //不包含有效cookie则跳转至登录
      return redirect('/login');
    }

    public function videoCenter(Request $request){
      $phone = $request->cookie('phone');
      $userId= $request->cookie('userId');
      //验证是否有cookie信息
      if($phone!=0 && $phone!=null){
        $data=['phone'=>$phone];
        // $rqUrl=$this->apiBaseUri.$this->apiVideoCateUri;
        // $rqData=['personal_mobile'=>$phone,'fromRequest'=>'tanwin'];
        // $result=$this->curl->to($rqUrl)
        // ->withOption('TIMEOUT', 10)
        // ->withData($rqData)
        // ->post();
        // print_r($result);
        $result=['code'=>100];//写死的部分
        $result=json_encode($result);//写死的部分
        try {
            $result=json_decode($result,true);
            if($result['code']==100){
              // $rData=$result['data'];
              $data['code']=1;
              // $data['data']=$rData;
              $data['phone']=$phone;
              $data['id']=$userId;
              return \response()
                   ->view('web.uc.video', $data)
                   ->withCookie(cookie('phone',$phone,120))
                   ->withCookie(cookie('userId',$userId,120));
            }
          } catch (Exception $e) {
            $data['code']=-1;
            $data['data']=null;
            $data['phone']=$phone;
            $data['id']=$userId;
            return \response()
                 ->view('web.uc.video', $data)
                 ->withCookie(cookie('phone',$phone,120))
                 ->withCookie(cookie('userId',$userId,120));
          }
        }

      //不包含有效cookie则跳转至登录
      return redirect('/login');
    }

    public function ajaxArticleList(Request $request){
      if(isset($request->pageNumber) && $request->pageNumber!=0)$pageNumber=$request->pageNumber;
      else $pageNumber=1;
      $pageSize=10;
      $categoryId=$request->categoryId;
      // $pageNumber=$this->msgPageNum;
      //验证是否有cookie信息
        $rqUrl=$this->apiBaseUri.$this->apiArticleListUri;
        $rqData=['article_programa_id'=>$categoryId,'fromRequest'=>'tanwin','pageNumber'=>$pageNumber,'pageSize'=>$pageSize];
        $result=$this->curl->to($rqUrl)
        ->withOption('TIMEOUT', 10)
        ->withData($rqData)
        ->post();
        // print_r('请求地址是'.$rqUrl.'</br>');
        // print_r('请求结果是'.$result);
        try {
            $result=json_decode($result,true);
            if($result['code']==100){
              $rData=$result['data'];
              $data['code']=1;
              $data['data']=$rData;
              return response(json_encode($data));
            }
          } catch (Exception $e) {
            $data['data']=null;
            $data['code']=-1;
            return response(json_encode($data));
          }
      }

      public function infoT(Request $request){
          $id=$request->id;
          $cid=$request->cid;
          // if($cid>4||$cid<=0||$cid==null)return redirect('/404');
          if($id!=0){
            try {
              $rqUrl=$this->apiBaseUri.$this->apiArticleUri;
              $rqData=['id'=>$id];
              $result=$this->curl->to($rqUrl)
              ->withOption('TIMEOUT', 10)
              ->withData($rqData)
              ->post();
              $viewData=json_decode($result,true);
              $viewData['tag']='twnews';
              $viewData['cid']=$cid;
              return view('web.common.infoT', $viewData);
            } catch (Exception $e) {
              return response("哎呀出错了！联系管理员！");
            }
          }
          return response("哎呀出错了！联系管理员！");
      }
}
